package com.guet.niit.Login.controller.admin;

import com.guet.niit.Admin.dao.AgentDaolmpl;
import com.guet.niit.Admin.dao.ChargingDaolmpl;
import com.guet.niit.Admin.dao.ChargingPileDaolmpl;
import com.guet.niit.Admin.dao.UserDaolmpl;
import com.guet.niit.Admin.pojo.Agent;
import com.guet.niit.Admin.pojo.Charging;
import com.guet.niit.Admin.pojo.ChargingPile;
import com.guet.niit.Admin.pojo.User;
import com.guet.niit.Login.pojo.AgentData;
import com.guet.niit.Login.pojo.StationData;
import com.guet.niit.util.adminSwitchoverMenu;
import com.guet.niit.util.exitLogin;
import com.sun.javafx.stage.StageHelper;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

public class AgentManageFxController implements Initializable {
    public static AgentManageFxController agentManageFxController;

    @FXML
    private MenuItem stationManage;

    @FXML
    private MenuItem stationPileManage;

    @FXML
    private MenuItem userManage;

    @FXML
    private MenuItem mainMenu;

    @FXML
    private MenuItem exit;

    @FXML
    private TableView<AgentData> tableView;
    private ObservableList<AgentData> data = FXCollections.observableArrayList();

    @FXML
    private TableColumn<AgentData, Long> tc_agentId;

    @FXML
    private TableColumn<AgentData, String> tc_agentName;

    @FXML
    private TableColumn<AgentData, String> tc_password;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        agentManageFxController = this;
    }

    /**
     * 通过菜单子项进入充电站管理
     * @param actionEvent
     */
    public void enterStationManageByMenuItem(ActionEvent actionEvent) {
        String text = stationManage.getText();
        adminSwitchoverMenu.backtrack(AgentManageFxController.class,text);
        //调用dao层查询充电站表
        ChargingDaolmpl chargingDao = new ChargingDaolmpl();
        List<Charging> stations = chargingDao.chargingInquire();
        //读取充电站列表信息
        ChargingStationManageFxController.chargingStationManageFxController.readStationsInfo(stations);
    }

    /**
     * 通过菜单子项进入充电桩管理
     * @param actionEvent
     */
    public void enterStationPileManageByMenuItem(ActionEvent actionEvent) {
        String text = stationPileManage.getText();
        adminSwitchoverMenu.backtrack(AgentManageFxController.class,text);
        //调用dao层查询充电桩表
        ChargingPileDaolmpl chargingPileDao = new ChargingPileDaolmpl();
        List<ChargingPile> chargingPiles = chargingPileDao.chargingPileInquire();

        //读取充电桩列表信息
        ChargingPileManageFxController.chargingPileManageFxController.readStationPileInfo(chargingPiles);
    }

    /**
     * 通过菜单子项进入用户管理
     * @param actionEvent
     */
    public void enterUserManageByMenuItem(ActionEvent actionEvent) {
        String text = userManage.getText();
        adminSwitchoverMenu.backtrack(AgentManageFxController.class,text);
        //调用dao层查询用户表
        UserDaolmpl userDao = new UserDaolmpl();
        List<User> users = userDao.userInquire();

        //读取用户列表信息
        UserManageFxController.userManageFxController.readUserInfo(users);
    }

    /**
     * 通过菜单子项进入主菜单
     * @param actionEvent
     */
    public void enterMainMenuByMenuItem(ActionEvent actionEvent) {
        String text = mainMenu.getText();
        adminSwitchoverMenu.backtrack(AgentManageFxController.class,text);
    }

    /**
     * 点击菜单项的退出项退出系统
     * @param actionEvent
     */
    public void clickExit(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(null);
        alert.setContentText("您确定要退出吗？");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK){
//            Platform.exit();
            exitLogin.backtrack(AgentManageFxController.class);
        }else {
            alert.close();
        }
    }

    /**
     * 读取代理商列表信息
     * @param agents
     */
    public void readAgentInfo(List<Agent> agents){
        setTableDataAfterSelectAll(agents);
    }

    /**
     * 查询所有时设置代理商表格数据
     * @param agents
     */
    public void setTableDataAfterSelectAll(List<Agent> agents){
        //转存数据
        for (int i = 0; i < agents.size(); i++) {
            //转存代理商id
            Long oriAgentId = agents.get(i).getId();
            LongProperty agentId = new SimpleLongProperty(oriAgentId);
            //转存代理商名
            String oriAgentName = agents.get(i).getUsername();
            StringProperty agentName = new SimpleStringProperty(oriAgentName);
            //转存密码
            String oriPassword = agents.get(i).getPassword();
            StringProperty password = new SimpleStringProperty(oriPassword);
            //装入数据模型
            data.add(new AgentData(agentId,agentName,password));
        }

        //绑定数据
        tc_agentId.setCellValueFactory(new PropertyValueFactory<AgentData,Long>("agentId"));
        tc_agentName.setCellValueFactory(cellData -> cellData.getValue().agentNameProperty());
        tc_password.setCellValueFactory(cellData -> cellData.getValue().passwordProperty());
        tableView.setItems(data);
    }

    /**
     * 点击按钮新增数据
     * @param mouseEvent
     */
    public void AddRowData(MouseEvent mouseEvent) {
        //引用fxml样式
        Parent load = null;
        try {
            load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyAgentData.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));
    }

    /**
     * 点击按钮修改数据
     * @param mouseEvent
     */
    public void updateRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        AgentData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("修改失败!");
            alert.setContentText("原因：您还没有选择需要修改的行");
            alert.showAndWait();
        }else {
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyAgentData.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            ObservableList<Stage> stageList = StageHelper.getStages();
            stageList.get(0).setScene(new Scene(load));
            //回显原数据
            ModifyAgentDataFxController.modifyAgentDataFxController.showData(selectedItem);
        }
    }

    /**
     * 点击按钮删除数据
     * @param mouseEvent
     */
    public void deleteRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        AgentData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("删除失败!");
            alert.setContentText("原因：您还没有选择需要删除的行");
            alert.showAndWait();
        }
        //获取要删除数据的id
        long agentId = selectedItem.getAgentId();
        //调用service层删除数据
        AgentDaolmpl agentDao = new AgentDaolmpl();
        boolean condition = agentDao.agentDelete(agentId);
        if (condition){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText(null);
            alert.setContentText("删除成功!");
            alert.showAndWait();
            //更新数据
            //调用dao层查询代理商表
            List<Agent> agents = agentDao.agentInquire();

            //读取代理商列表信息
            setTableDataAfterDeletedData(agents);
        }
    }

    /**
     * 清空表格中原有的数据
     */
    public void emptyData(){
        //清空原有数据
        for (int i = 0; i < data.size(); i++) {
            data.remove(i);
            i--;
        }
    }

    /**
     * 删除数据后设置充电站表格数据
     * @param agents
     */
    public void setTableDataAfterDeletedData(List<Agent> agents) {
        //清空原有数据
        emptyData();
        //更新数据
        setTableDataAfterSelectAll(agents);
    }

    /**
     * 关于我们
     * @param actionEvent
     */
    public void aboutUs(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("关于我们");
        alert.setContentText("充电桩管理系统由Power-station项目组人员开发，本管理系统目前已实现四个模块的增删改查。");
        alert.showAndWait();
    }
}
